package org.duang.db.common;

import java.util.Map;

import org.duang.db.mongo.Operator;
import org.duang.db.mongo.parser.EncodeConvetor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

/**
 * Mongodb的更新对象
 * @author laotang
 */
public class Update {
	
	private final static Logger logger = LoggerFactory.getLogger(Update.class);

	private DBObject updateObj;
	private Map<String, Object> dboMap;
	
	public Update(){
		dboMap = new java.util.LinkedHashMap<String, Object>();
	}

	public DBObject getUpdateObj() {
		if(dboMap.size() > 1){
			set(dboMap);
		}
		
		logger.debug(" update: " + updateObj.toString());
		return updateObj;
	}
	
	
	/**
	 * 将符合查询条件的key更新为value
	 * @param key		要更新列名
	 * @param value		更新后的值
	 * @return
	 */
	public Update set(String key, Object value) {
		DBObject dbo = new BasicDBObject(key, value);
		updateObj = new BasicDBObject(Operator.SET, dbo);
		dboMap.put(key, value);
		return this;
	}
	
	/**
	 * 将值添加到符合查询条件的对象中
	 * @param key		要添加列名
	 * @param value		要添加的值
	 * @return
	 */
	public Update push(String key, Object value) {
		value = EncodeConvetor.convetor(value);
		DBObject dbo = new BasicDBObject(key, value);
		updateObj = new BasicDBObject(Operator.PUSH, dbo);
		dboMap.put(key, value);
		return this;
	}
	
	/**
	 * 将符合查询条件的值从array/list/set中删除
	 * @param key		要删除列名
	 * @param value		要删除的值
	 * @return
	 */
	public Update pull(String key, Object value) {
		value = EncodeConvetor.convetor(value);
		DBObject dbo = new BasicDBObject(key, value);
		updateObj = new BasicDBObject(Operator.PULL, dbo);
		dboMap.put(key, value);
		return this;
	}
	
	/**
	 * 批量更新符合查询的值
	 * @param values	需要更新key，value的Map集合, key为字段名，value
	 * @return
	 */
	public Update set(Map<String, Object> values) {
		DBObject dbo = new BasicDBObject(values);
		updateObj = new BasicDBObject(Operator.SET, dbo);
		return this;
	}
	
	public Update inc(String key, Object value) {
		DBObject dbo = new BasicDBObject(key, value);
		updateObj = new BasicDBObject(Operator.INC, dbo);
		return this;
	}
	
}
